package my_web.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import Proxy.DynamicProxy;
import ReqBean.RequestBean;
import my_web.Interface.EmpInterface;
import my_web.bean.Dep;
import my_web.bean.Emp;
import my_web.bean.Pos;
import my_web.model.EmpDto;
import my_web.service.EmpService;
@MultipartConfig
public class EmpServlet extends HttpServlet {
	//处理get方式的请求
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//设置请求和响应的编码格式
		req.setCharacterEncoding("utf-8");
		res.setCharacterEncoding("utf-8");
		//获取请求的路径
		String path=req.getServletPath();
		//建立业务类对象
		//EmpInterface service=new EmpService();
		EmpInterface  service = null;
		try {
			service=DynamicProxy.creatServiceProxy(EmpInterface.class, EmpService.class);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		if("/EmpToList.do".equals(path)){
			try {
				EmpDto dto=RequestBean.getBeanFromRequest(EmpDto.class, req);
				req.setAttribute("pg",service.DynamicQueryAllEmps(dto));
				req.getRequestDispatcher("EmpList.jsp").forward(req, res);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}else if("/EmpToAdd.do".equals(path)){
			//通过业务对象获取所有的部门信息
			List<Dep> Deps=service.getAllDeps();
			req.setAttribute("DepList",Deps);
			//通过业务对象获取所有的职位信息
			List<Pos> Poss=service.getAllPoss();
			req.setAttribute("PosList",Poss);
			//重新转发
			req.getRequestDispatcher("EmpAdd.jsp").forward(req, res);
		}else if("/EmpDoAdd.do".equals(path)){
			//创建员工记录
			//Emp emp=new Emp();
			try {
				EmpDto dto=RequestBean.getBeanFromRequest(EmpDto.class, req);
				dto.setD_id(req.getParameter("bumen"));
				dto.setP_id(req.getParameter("zhiwei"));
				service.addEmp(dto);
				res.sendRedirect("EmpToList.do");
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}else if("/EmpDoDel.do".equals(path)){
			res.setContentType("application/json;charset=utf-8");
			PrintWriter out=res.getWriter();
			try {
				String e_id=req.getParameter("e_id");
				service.removeEmpById(e_id);
				out.print("{\"success\":true,\"msg\":\"删除成功！\"}");
			} catch (Exception e) {
				e.printStackTrace();
				out.print("{\"success\":false,\"msg\":\"删除失败！\"}");
			}
			out.flush();
			out.close();
			//res.sendRedirect("EmpToList.do");
		}else if("/EmpDoMultiDel.do".equals(path)){
			String[]e_ids=req.getParameterValues("e_ids");
			service.removeEmpById(e_ids);	
			res.sendRedirect("EmpToList.do");
		}else if("/EmpToUpd.do".equals(path)){
			List<Dep> Deps=service.getAllDeps();
			req.setAttribute("DepList",Deps);
			List<Pos> Poss=service.getAllPoss();
			req.setAttribute("PosList",Poss);
			String e_id=req.getParameter("e_id");
			Emp emp=service.getEmpById(e_id);
			req.setAttribute("Emp", emp);
			req.getRequestDispatcher("EmpUpd.jsp").forward(req, res);
		}else if("/EmpDoUpd.do".equals(path)){
			EmpDto dto;
			try {
				dto = RequestBean.getBeanFromRequest(EmpDto.class, req);
				dto.setD_id(req.getParameter("bumen"));
				dto.setP_id(req.getParameter("zhiwei"));
				service.modifyEmp(dto);
				res.sendRedirect("EmpToList.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if ("/uploadImages.do".equals(path)) {
			Emp emp = (Emp)req.getSession().getAttribute("Emp");//获取当前登录的用户，即emp对象
			Part part = req.getPart("upfile");//获取上传文件的文件数据
			InputStream in = part.getInputStream();//获取读取文件的输入流
			//获取文件的content-disposition(包括form-data; name="upfile"; filename="甘小敏.jpg")
			String content_disposition = part.getHeader("content-disposition");
			System.out.println("content_disposition:"+content_disposition);
			/**
			 * String 常用方法说明
			 * 1.public int indexOf(int ch)：返回指定字符在此字符串中第一次出现处的索引
			 * 2.public String substring(int beginIndex,int endIndex)：返回一个新字符串，它是此字符串的一个子字符串
			 * 该子字符串从指定的 beginIndex处开始，直到索引 endIndex-1 处的字符。因此，该子字符串的长度为 endIndex-beginIndex
			 */
			String filename=content_disposition.substring(content_disposition.indexOf("filename=")+10, content_disposition.length()-1);
			//通过指定的文件路径创建文件对象：D/fileupload
			File file = new File("D:" + File.separator + "fileupload"+File.separator+filename);
			OutputStream out = new FileOutputStream(file);//字节输出流
			int k = -1;
			byte b[] = new byte[1024 * 1024];
			while ((k = in.read(b)) != -1) {
				out.write(b, 0, k);
			}
			in.close();
			out.flush();
			out.close();
			try {
				emp.setImage(filename);//把修改的图片名称设置给emp的image属性
				service.updateImages(emp);//调用方法，更新emp对象对应的image属性
			} catch (Exception e) {
				e.printStackTrace();
			}
			res.sendRedirect("myInfo.jsp?time="+new Date().getTime());
		}else if("/showImages.do".equals(path)){
			Emp emp = (Emp)req.getSession().getAttribute("Emp");//获取Emp对象
			OutputStream out  = res.getOutputStream();//输出流
			String imagePath = "D:"+File.separator+"fileupload"+File.separator+emp.getImage();//图片地址
			System.out.println(imagePath);
			InputStream in = new FileInputStream(new File(imagePath));//输入流
			int len = -1;
			byte[] bs = new byte[1024*1024];
			while((len=in.read(bs))!=-1){
				out.write(bs,0,len);
			}
			in.close();
			out.flush();
			out.close();
		}
	}
	//处理post方式的请求
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.doGet(req, res);
	}
}
